<template>
  <div>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/admin/home">首页</el-breadcrumb-item>
        <el-breadcrumb-item to="/admin/article">博客管理</el-breadcrumb-item>
        <el-breadcrumb-item>编辑文章</el-breadcrumb-item>
        <el-button class="back" type="primary" size="mini" @click="$router.back()">返回</el-button>
      </el-breadcrumb>
      <el-card
        ><el-form ref="EditorBlog" :model="article" label-width="80px" :rules="articleRules">
          <el-form-item label="博客标题" prop="tittle">
            <el-input v-model="article.tittle"></el-input>
          </el-form-item>
          <el-form-item label="博客封面" prop="image_address"> <img class="blogimg" :src="article.image_address" alt="" /></el-form-item>
          <el-form-item label="博客作者" prop="author">
            <el-input v-model="article.author"></el-input>
          </el-form-item>
          <el-form-item label="博客分类" prop="category_id">
            <el-select v-model="article.category_id" placeholder="请选择博客分类">
              <el-option v-for="item in category" :key="item.id" :label="item.alias" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="博客摘要" prop="abstract">
            <el-input type="textarea" v-model="article.abstract"></el-input>
          </el-form-item>
          <el-form-item label="博客内容" prop="content">
            <quillEditor class="editor" ref="articleEditor" v-model="article.content" :options="editorOption" @change="quillEditorchange($event)"></quillEditor>
            <input type="file" hidden accept=".png, .jpg, .JPG, .JPEG, .jpeg, .PNG .GIF, .gif" ref="fileBtn" @change="insertImg"
          /></el-form-item>
          <el-form-item label="添加博客">
            <el-button type="primary" @click="editorBlog">提交</el-button>
            <el-button @click="cancelEdiorBlog">取消修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'BackEndArticleEditor',
  components: { quillEditor },
  data() {
    return {
      editorOption: {
        // 占位配置
        placeholder: '请在这里输入blog内容',
        modules: {
          imageDrop: true,
          imageResize: {
            //放大缩小
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
          // 配置工具栏
          toolbar: [
            ['bold', 'strike'], //加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], //引用  代码块
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
            [{ color: [] }, { background: [] }], // 颜色选择
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['image', 'video', 'link'], //链接、图片、视频
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ font: ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }] // 字体
          ]
        }
      },
      article: {
        tittle: '',
        author: '',
        category_id: '',
        abstract: '',
        content: '',
        image_address: ''
      },
      id: 0,
      category: [],
      articleRules: {
        tittle: [{ required: true, message: '博客标题不能为空', trigger: 'blur' }],
        author: [{ required: true, message: '博客作者不能为空', trigger: 'blur' }],
        category_id: [{ required: true, message: '请选择博客分类', trigger: 'change' }],
        abstract: [{ required: true, message: '博客摘要不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '博客内容不能为空', trigger: 'blur' }],
        image_address: [{ required: true, message: '请上传博客封面', trigger: 'blur' }]
      }
    }
  },
  async created() {
    this.id = this.$route.params.id
    if (this.id == 0) {
      return
    }
    const { result } = await this.$http.get(`/article/${this.id}`)
    this.article = result[0]
    this.getCategories()
  },
  mounted() {
    if (this.$refs.articleEditor) {
      //myQuillEditor改成自己的
      this.$refs.articleEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    }
  },
  computed: {},
  methods: {
    quillEditorchange(e) {
      this.article.content = e.html
    },
    async getCategories() {
      const { result } = await this.$http.get('/categories/all')
      this.category = result.data
    },
    async editorBlog() {
      this.$refs['EditorBlog'].validate(async valid => {
        if (valid) {
          const { message } = await this.$http.put(`/article/${this.id}`, {
            tittle: this.article.tittle,
            author: this.article.author,
            category_id: this.article.category_id,
            abstract: this.article.abstract,
            content: this.article.content,
            image_address: this.article.image_address
          })
          this.$message({
            type: 'success',
            message: message,
            duration: 1000
          })
          this.$router.push('/admin/article')
        }
      })
    },
    cancelEdiorBlog() {
      this.$router.push('/admin/article')
    },
    imgHandler() {
      this.$refs.fileBtn.click()
    },
    async insertImg(e) {
      const files = Array.prototype.slice.call(e.target.files)
      if (!files) {
        return
      }
      let formdata = new FormData()
      formdata.append('file', files[0])
      //使用了axios请求
      const data = await this.$http.post('/article/upload', formdata)
      let selection = this.$refs.articleEditor.quill.getSelection()
      //这里就是返回的图片地址，如果接口返回的不是可以访问的地址，要自己拼接
      let imgUrl = data.path
      //获取quill的光标，插入图片
      this.$refs.articleEditor.quill.insertEmbed(selection != null ? selection.index : 0, 'image', imgUrl)
      //插入完成后，光标往后移动一位
      this.$refs.articleEditor.quill.setSelection(selection.index + 1)
    }
  }
}
</script>

<style scoped>
.back {
  float: right;
  margin-bottom: 10px;
  margin-right: 10px;
}
.editor {
  line-height: normal !important;
  /* height: 250px; */
}
.blogimg {
  width: 80px;
  height: 80px;
}
</style>
